package com.straw.hat.jdk.jvm.hotloading;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @auth:yangbb
 * @date: 2019/11/10
 * @time: 21:42
 * @company: 海贼王
 * @describe:需要打破双亲模式
 */
public class HotLoadClassLoader extends ClassLoader{


    public static final String SUFFIX_CLASS = "class";

    /*
    * 制定加载的路径
    * */
    private static String rootPath ;

    {
        /*获取到运行期classes包的绝对路径*/
        String path = HotLoadClassLoader.class.getResource("/").getPath().replaceAll("%20", "");
        rootPath = new File(path).getPath();
        System.out.println("root path : "+ rootPath);
    }


    /**
     * 制定加载的class
     */
    private volatile List<String> classNameCache;

    /**
    * 只加载一次的限制
    * */
    private AtomicBoolean loading = new AtomicBoolean(Boolean.FALSE);



    public HotLoadClassLoader(String ... classPaths) {
        try {
            if (classPaths == null ) {
                throw new RuntimeException("parameters is bad");
            }
            if (loading.get()) {
                throw new RuntimeException("loading is running");
            }
            classNameCache = new ArrayList();
            for (String classPath : classPaths) {
                if (classPath == null) {
                    continue;
                }
                /*加载制定路径下的类到虚拟机中*/
                String loadPath = rootPath + "\\" + classPath;
                System.out.println("load path : "+loadPath);
                loadClassPath(new File(loadPath));
                System.out.println("load cache size : "+classNameCache.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 破坏双亲委派模式(反向破坏模式)
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        /*先从命名空间缓存查找*/
        Class<?> aClass = findLoadedClass(name);
        if (aClass == null) {
            if (!classNameCache.contains(name)) {
                /*交给系统类加载器加载*/
                aClass = getSystemClassLoader().loadClass(name);
            } else {
                throw new RuntimeException("not found this class :　"+name);
            }
        }
        return aClass;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }
    /**
     *加载类文件到虚拟机中
     * @param file
     * @throws Exception
     */
    public void loadClassPath (File file) throws Exception {
        if (file == null) {
            return;
        }
        if (file.isDirectory()) {
            for (File childrenFile : file.listFiles()) {
                loadClassPath(childrenFile);
            }
        } else {
            String name = file.getName();
            String path = file.getPath();
            String suffixName = name.substring(name.lastIndexOf(".") + 1);
            if (suffixName.endsWith(SUFFIX_CLASS)) {
                InputStream inputStream = new FileInputStream(file);
                byte [] bytes = new byte[(int) file.length()];
                inputStream.read(bytes);
                String className = filePathToClassName(path);
                /*保存到缓存中*/
                classNameCache.add(className);
                /*实现class文件到class类的操作*/
                defineClass(className,bytes,0,bytes.length);
            }
        }
    }

    /**
     * 根据路径的名称获取类名
     * @param filePathName
     * @return
     */
    public String filePathToClassName(String filePathName){
        String className = filePathName.replace(rootPath, "").replace("\\", ".");
        if (className == null) {
            return null;
        }
        className = className.substring(0, className.lastIndexOf("."));
        className = className.substring(1);
        return className;
    }




    public String getRootPath() {
        return rootPath;
    }

    public void setRootPath(String rootPath) {
        this.rootPath = rootPath;
    }

    public List<String> getClassNameCache() {
        return classNameCache;
    }

    public void setClassNameCache(List<String> classNameCache) {
        this.classNameCache = classNameCache;
    }
}
